<?php

/**
 * xunSearch 索引处理
 * @author  xiaobai
 * @date    2019-05-16
 */

namespace app\common\logic;

use app\common\model\Common;
use XS;
use XSDocument;

class Search extends Common
{
    /**
     * 写入文章迅搜索引
     * @param array $new_data   添加文章内容
     */
    public function setNewsIndex($new_data = [], $is_up = 0)
    {
        // 实例化迅搜
        $xs    = new XS('news');
        $index = $xs->index;
        // 整理迅搜索引所需文章信息
        $is_original = isset($new_data['is_original']) && $new_data['is_original'] != '' ? $new_data['is_original'] : 1;
        $data = [
            'id'          => $new_data['id'],
            'column_id'   => $new_data['column_id'],
            'title'       => $new_data['title'],
            'keywords'    => $new_data['keywords'],
            'description' => $new_data['description'],
            'read_number' => $new_data['read_number'],
            'author'      => $new_data['author'],
            'is_original' => $is_original,
            'create_time' => $new_data['create_time'],
        ];

        // 创建文档对象，默认字符集utf-8
        $doc = new XSDocument;
        $doc->setFields($data);

        $date_time = date('Y-m-d H:i:s');
        if ($is_up == 0) {
            // 添加到索引数据库中
            $res = $index->add($doc);
            $log = '___Add___ date:'.$date_time;
        } else {
            // 更新到索引数据库中
            $res = $index->update($doc);
            $log = '___Update___ date:'.$date_time;
        }
        $log = $log.'; data: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . '; 返回信息：' . json_encode($res, JSON_UNESCAPED_UNICODE);
        printLog($log, 'xun_search/news');
    }

    /**
     * 删除迅搜的文章索引
     * @param int $new_id   文章id
     */
    public function delNewsIndex($new_id = 0)
    {
        // 实例化迅搜
        $xs     = new XS('news');
        $index  = $xs->index;
        $result = $index->del($new_id);
        $logStr = '___Delete___ date: '.date('Y-m-d H:i:s').'; new_id: ' . $new_id . '; 返回信息：' . json_encode($result, JSON_UNESCAPED_UNICODE);
        printLog($logStr, 'xun_search/news');
    }

}
